Karma is a Javascript test-runner built with Node.js. Karma runs tests with browsers and is meant for unit testing.
Karma does not support Node.js testing at the moment.
Karma runs on Node.js and is available as an NPM package.
The recommended approach is to install Karma locally in the project's directory.
npm install karma --save-dev
command in your project's directory.npm install karma-jasmine karma-chrome-launcher --save-dev
command.npm install -g karma-cli
command.Create a configuration file for Karma.
Run karma init conf.js
command. conf.js is the file name of the configuration file and can be whatever.
Karma will first ask which framework to use. Jasmine is used in this example.
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine
The second setting is about whether to use Require.js. Choose no in this example.
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
The third setting is about the browser for testing. Choose chrome in this example.
Do you want to capture a browser automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>
The fourth setting is about the location of the source and test files. Use js/*.js
in this example.
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> js/*.js
>
The fifth setting is about excluding files. Nothing is set in this example.
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>
The final setting is about letting Karma re-run the tests if any file is changed.
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes
Seeing the following message means the configuration is finished.
Config file generated at "/Users/vojta/Code/karma/my.conf.js".
The example in the previous chapter (jasmine) is used in this example.
sum.js
and SumTestSpec.js
) in the /js
directory.karma start conf.js
command in the project's directory.Chrome 41.0.2272 (Linux): Executed 5 of 5 SUCCESS (0.011 secs / 0.003 secs)
shown in the terminal.karma start conf.js --single-run
command instead.To generate a test report in JUnit format, conf.js
needs to be changed.
First, install JUnit reporter plugin with npm install karma-junit-reporter --save-dev
command.
Second, change reporters: ['progress'],
(probably in line 36) to
reporters: ['dots', 'junit'],
junitReporter: {
outputFile: 'test-results.xml'
},
and change singleRun: false
to singleRun: true
Finally, run karma start conf.js
command and a test report test-results.xml
will be generated.
This report can be published to Jenkins.